package com.yanqu.road.server.cmd.union.cross.huaben;

import com.yanqu.road.entity.union.huaben.UnionHuaBenPassWeekData;
import com.yanqu.road.pb.union.cross.UnionHuaBenProto;
import com.yanqu.road.server.cmd.CrossCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.union.CrossUnionReqContext;
import com.yanqu.road.server.manager.union.huaben.CrossUnionHuaBenConfigMgr;
import com.yanqu.road.server.manager.union.huaben.CrossUnionHuaBenMgr;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.date.DateHelper;

@Cmd(code = Protocol.C_CROSS_UNION_HUA_BEN_GET, desc = "话本数据请求")
public class CrossUnionHuaBenWeekDataCmd extends CrossCommand {

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        return true;
    }

    @Override
    public void execute(YanQuMessage packet) throws Exception {

        CrossUnionReqContext context = CrossUnionReqContext.initContext(serverId, packet.getPlayerId()).loadUnionMember().loadUnionInfo();
        if(context.getRet() != 0){
            MessageHelper.sendPacket(serverId, packet.getPlayerId(), YanQuMessageUtils.buildMessage(Protocol.U_CROSS_UNION_HUA_BEN_GET, UnionHuaBenProto.UnionHuaBenWeekDataRespMsg.newBuilder().setRet(context.getRet())));
            return;
        }
        int weekId = CrossUnionHuaBenConfigMgr.getThisWeekId();

        UnionHuaBenPassWeekData weekData = CrossUnionHuaBenMgr.getUnionHuaBenPassWeekData(weekId, context.getUnionInfo().getServerId(), context.getUnionInfo().getUnionUid());
        if(weekData != null){
            if (weekData.getOpenTime() + weekData.getDuration() * DateHelper.MINUTE_SECONDS < DateHelper.getCurrentSecond()) {
                synchronized (weekData) {
                    CrossUnionHuaBenMgr.settleWeekData(weekData);
                }
                CrossUnionHuaBenMgr.syncHuaBenData(context.getUnionInfo(), weekData);
            }else {
                CrossUnionHuaBenMgr.syncHuaBenData(context.getUnionInfo(), context.getMember(), weekData);
            }
            CrossUnionHuaBenMgr.syncMemberData(context.getMember().getServerId(), context.getPlayerId());
            CrossUnionHuaBenConfigMgr.syncConfig(context.getUnionInfo());
        }else {
            CrossUnionHuaBenMgr.syncHuaBenData(context.getUnionInfo(), context.getMember(), null);
        }

        MessageHelper.sendPacket(serverId, packet.getPlayerId(), YanQuMessageUtils.buildMessage(Protocol.U_CROSS_UNION_HUA_BEN_GET, UnionHuaBenProto.UnionHuaBenWeekDataRespMsg.newBuilder().setRet(0)));
    }

    @Override
    public void sendData() {

    }
}
